<template>
  <div class="header">
    <div class="logo">
      <img src="../../assets/img/head-logo.svg" alt="">
    </div>
    <ul class="nav">
      <li v-for="(item, index) in state.nav_list" :key="index">
        <a :href="item.link">
          {{ item.title }}
        </a>
      </li>
    </ul>
    <div class="login" v-if="state.token">
      <div class="shop-cart">
        <el-badge :value="state.cart_count" class="item" type="warning">
          <img src="../../assets/img/cart.svg" alt="">
        </el-badge>
        <span>购物车</span>
      </div>
      <div class="login-right">
        <el-menu class="el-menu-demo" mode="horizontal">
          <el-submenu index="1">
            <template #title>学习中心</template>
            <el-menu-item index="1-1">我的账户</el-menu-item>
            <el-menu-item index="1-2">我的订单</el-menu-item>
            <el-menu-item index="1-3">我的优惠券</el-menu-item>
            <el-menu-item index="1-4">
              <span @click="logout">退出登录</span>
            </el-menu-item>
          </el-submenu>
        </el-menu>
      </div>
    </div>
    <div class="login" v-else>
      <Login/>
      <span class="sep">|</span>
<!--      <a href="#">注册</a>-->
      <Register/>
    </div>
  </div>
</template>

<script>
import {reactive, onMounted, inject} from "vue"

import {getNavs} from "@/api/home";
// import Login from "@/components/Login";
// import Register from "@/components/Register";

export default {
  name: "MyHeader",
  // components: {Login, Register},
  setup() {
    const state = reactive({
      cart_count: 0,
      nav_list: [],
      token: localStorage.user_token || sessionStorage.user_token
    })

    onMounted(() => {
      getNavs().then(res => {
        state.nav_list = res.data
      })
    })

    const reload = inject('reload')

    function logout(){
      localStorage.removeItem('user_token')
      localStorage.removeItem('user_id')
      localStorage.removeItem('user_name')

      sessionStorage.removeItem('user_token')
      sessionStorage.removeItem('user_id')
      sessionStorage.removeItem('user_name')

      // location.reload()
      reload()
    }

    return {
      state,
      logout
    }
  }
}
</script>

<style scoped>
.header {
  height: 60px;
  width: 90%;
  margin: 0 auto;

  display: flex;
  align-items: center;
}

.header .nav {
  display: flex;
  margin-left: 50px;
}

.header .nav li {
  margin-right: 20px;
}

.header .nav li a {
  display: inline-block;
  height: 36px;
  line-height: 36px;
  border-bottom: 2px solid transparent;
}

.header .nav li a:hover {
  border-bottom: 2px solid #ffc210;
}

.header .login {
  margin-left: auto;
  font-size: 14px;
  display: flex;
  align-items: center;
}

.header .login .sep {
  margin: 0 10px;
}

.header .login a:hover {
  color: #ffc210;
}
</style>